//
//  DMProductManager.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/7/15.
//

#import "DMProductManager.h"
#import "IMLogUtils.h"

#define kDMProductCacheKey @"DMProductCacheKey"
#define kDMProductCacheTimestampKey @"DMProductCacheTimestamp"
#define kDMProductCacheTTL 86400  // 缓存有效期（单位：秒，默认 1 天）

@interface DMProductManager ()

@property (nonatomic, strong) SKProductsRequest *productsRequest;

@end

@implementation DMProductManager

+ (instancetype)sharedManager {
    static DMProductManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[DMProductManager alloc] init];
    });
    return manager;
}

- (void)requestProductsWithIdentifiers:(NSArray<NSString *> *)productIds {
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 开始请求商品列表，商品ID数量: %lu", (unsigned long)productIds.count];
    
    // 如果本地缓存有效，优先返回
    NSArray *cachedData = [self loadCachedProducts];
    if (cachedData.count > 0) {
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 使用缓存数据，商品数量: %lu", (unsigned long)cachedData.count];
        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didReceiveProductList:)]) {
            // 传递不可变副本，避免外部遍历时修改导致崩溃
            [self.delegate dmAdManager:nil didReceiveProductList:[cachedData copy]];
        }
    }

    // 发起新的请求（刷新缓存）
    NSSet *productSet = [NSSet setWithArray:productIds];
    self.productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productSet];
    self.productsRequest.delegate = self;
    [self.productsRequest start];
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 已发起商品信息请求"];
}

#pragma mark - SKProductsRequestDelegate

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    NSArray<SKProduct *> *products = response.products;
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 商品请求成功，获取到商品数量: %lu", (unsigned long)products.count];
    
    if (products.count > 0) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didReceiveProductList:)]) {
            // 传递不可变副本，避免外部遍历时修改导致崩溃
            [self.delegate dmAdManager:nil didReceiveProductList:[products copy]];
        }
        
        // 缓存数据
        NSData *archived = [NSKeyedArchiver archivedDataWithRootObject:products requiringSecureCoding:NO error:nil];
        [[NSUserDefaults standardUserDefaults] setObject:archived forKey:kDMProductCacheKey];
        [[NSUserDefaults standardUserDefaults] setDouble:[[NSDate date] timeIntervalSince1970] forKey:kDMProductCacheTimestampKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 商品数据已缓存"];
    } else {
        NSError *error = [NSError errorWithDomain:@"DMProductManager" code:-1 userInfo:@{NSLocalizedDescriptionKey: @"未获取到任何商品信息"}];
        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToReceiveProductList:)]) {
            [self.delegate dmAdManager:nil didFailToReceiveProductList:error];
        }
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 商品请求失败：未获取到任何商品信息"];
    }
}

#pragma mark - 缓存加载

- (NSArray<SKProduct *> *)loadCachedProducts {
    NSTimeInterval timestamp = [[NSUserDefaults standardUserDefaults] doubleForKey:kDMProductCacheTimestampKey];
    NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
    if (now - timestamp > kDMProductCacheTTL) {
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 缓存已过期，返回空数组"];
        return @[];
    }

    NSData *archived = [[NSUserDefaults standardUserDefaults] objectForKey:kDMProductCacheKey];
    if (archived) {
        NSArray *products = [NSKeyedUnarchiver unarchiveObjectWithData:archived];
        if ([products isKindOfClass:[NSArray class]]) {
            [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 成功加载缓存商品数据，数量: %lu", (unsigned long)products.count];
            // 返回不可变副本，避免外部修改导致与遍历冲突
            return [products copy];
        }
    }
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 未找到有效的缓存数据"];
    return @[];
}

@end
